package com.dqy.twserver.server.handle.ehandle;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.PlayerInfo;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;


public class GameEventLogingHandle implements  GameEventHandle{
    static Logger logger = LoggerFactory.getLogger(GameEventLogingHandle.class);
    @Override
    public void handle(GameDto req, NioSocketChannel channel) {
        logger.info("[GameEventLogingHandle] start");
        GameDto resp=new GameDto();

        String playerName = req.getPlayerName();
        String playerPass = req.getPlayerPass();
        PlayerInfo player = SupportMap.playerDataMap.get(playerName);
        if(player==null){
            resp.setSts(400);
            resp.setInfo("用户不存在");
            channel.writeAndFlush(resp);
            logger.info("[GameEventLogingHandle] 用户不存在");
            return;
        }
        if(!player.getPassWord().equals(playerPass)){
            resp.setSts(400);
            resp.setInfo("密码错误");
            channel.writeAndFlush(resp);
            logger.info("[GameEventLogingHandle] 密码错误");
            return;
        }

        //不可重复登录
        Map<String, Player> playerMap = SupportMap.playerMap;
        Player ortherPlayer = playerMap.get(playerName);
        if(ortherPlayer!=null){
            resp.setSts(400);
            resp.setInfo(String.format("该用户已经在%s机器上登录,不可重复登录",ortherPlayer.getSocketChannel().remoteAddress().getAddress()));
            channel.writeAndFlush(resp);
            logger.info("[GameEventLogingHandle] 不可重复登录");
            return;
        }

        Player playerConnect = new Player(playerName, channel);
        SupportMap.playerMap.put(playerName,playerConnect);
        resp.setSts(200);
        resp.setInfo("登录成功!");

        //channelIdMap保存改登录信息
        String cid = channel.id().toString();
        SupportMap.channelIdPlayMap.put(cid,playerConnect);

        channel.writeAndFlush(resp);
        logger.info("[GameEventLogingHandle] end");
    }
}
